(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('lfe.ppfRepayment.viewController', viewController);
	viewController.$inject = [ '$q', '$filter', '$scope', 'Constants', 'formatService', 'modalService', 'gridService', 'layoutConfig', 'validatorConfig', 'authService',
			'ppfRepaymentService', 'dateService', "arithService", 'commonService'];
	function viewController($q, $filter, $scope, Constants, formatService, modalService, gridService, layoutConfig, validatorConfig, authService, ppfRepaymentService, dateService, arithService, commonService) {
		var ctrl = this, params = $scope.$stateParams.params;
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.ppfRepaymentLoad = {};
		
		ctrl.init = function() {
			ctrl.innerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.loansCfg.tableConfigs.table);
			ctrl.innerGridOptions.data = 'vm.ppfRepaymentLoad.ppfRepayments';
			ctrl.innerGridOptions.enableRowHeaderSelection = false;
			ppfRepaymentService.getCurrencyOptions().then(function(response) {
				return $q(function(resolved, rejected) {
					ctrl.currencyOptions = response.data;
					resolved();
				});
			}).then(function() {
				return $q(function(resolved, rejected) {
					ppfRepaymentService.getPpfRepaymentStatusOptions().then(function(response) {
						ctrl.ppfRepaymentStatusOptions = response.data;
						resolved();
					});
				});
			}).then(function() {
				authService.view(params).then(function(response) {
					if (response.data) {
						ctrl.ppfRepaymentLoad= response.data;
					}
				});
			});
		};
		
		var watcher = $scope.$watch('vm.ppfRepaymentLoad.ppfRepayments.length', function(modelValue) {
			if(modelValue || modelValue == 0){
				ctrl.ppfRepaymentLoad.totalLoanAmt = calTotalLoanAmt(ctrl.ppfRepaymentLoad.ppfRepayments);
			}
		});
		$scope.$on('$destroy', function() {
			(watcher || angular.noop)();
		});
		
		function calTotalLoanAmt(ppfRepayments){
			var totalLoanAmt = 0;
			angular.forEach(ppfRepayments, function(value, key) {
				totalLoanAmt = parseFloat(arithService.add(totalLoanAmt, value.loanOutAmount));
			});
			return totalLoanAmt;
		};

	}
})(angular);
